﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using VanTaiBLL;
using VanTaiData;
using VanTaiProperty;
using Roles;
using System.Web.UI.HtmlControls;

namespace VanTaiTMS.Page
{
    public partial class don_vi_tinh_loai_xe : System.Web.UI.Page
    {
        #region[Define]
        private DataTable dtUnitVehicle;
        private DataTable dtUnitVehicleDetail;
        private DataTable dtBlockVehicle;
        private DataTable dtSearch;
        protected string SuggestionList;
        protected string StrAlert = "";
        private DataTable dtAutoComplete;
        private static bool flag = false;
        private clsTMUnit_VehicleBusiness clsUnitVehicle = new clsTMUnit_VehicleBusiness();
        private clsTMBock_VehicleBusiness clsBockVehicle = new clsTMBock_VehicleBusiness();
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermisstion();
            Autocomplate();
            if (!IsPostBack)
            {
                BindGridUnitVehicle();
                BindGridBlockVehicle();
            }
        }
        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            flag = true;
            lbThongBaoLoi.Text = "";
            txtMaDonViTinh.Enabled = true;
            ClearTextBox();
            ClearDropdownlist();
            OpenDialog("#donvitinhxe");
            imgSave.ToolTip = "Thêm mới";
            upNewUpdatePanel.Update();
            imgSave.Visible = true;
        }
        protected void cmdEdit_Click(object sender, EventArgs e)
        {
            lbThongBaoLoi.Text = "";
            txtMaDonViTinh.Enabled = false;
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                Label lbTrangThai = (Label)ListViewAll.Items[i].FindControl("lbDuyet");
                if (chkView != null)
                {
                    if (chkView.Checked)
                    {
                        BindGridUnitVehicleDetail_Edit(Convert.ToInt32(ListViewAll.DataKeys[i].Value.ToString()));
                        OpenDialog("#donvitinhxe");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                }
            }
        }
        protected void cmdDel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkHide = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                Label lbTrangThai = (Label)ListViewAll.Items[i].FindControl("lbDuyet");
                if (chkHide != null)
                {
                    if (chkHide.Checked)
                    {
                        try
                        {
                            if (clsUnitVehicle.TMUnit_Vehicle_Check_Delete_TMType_Vehicle(int.Parse(ListViewAll.DataKeys[i].Value.ToString())) == false)
                            {
                                VanTaiBLL.clsTMUnit_VehicleBusiness.DeleteTMUnit_Vehicle(int.Parse(ListViewAll.DataKeys[i].Value.ToString()));
                                BindGridUnitVehicle();
                            }
                            else
                            {
                                lbThongBaoXoa.Text = "Mẫu tin này vẩn còn tồn tại.Không thể xoá !";
                                OpenDialog("#thongbaoxoa");
                                upDatePanelThongBaoXoa.Update();
                                cmdAgree.Visible = false;
                                cmdClose.Text = "Đóng lại";
                            }
                        }
                        catch (Exception ex)
                        {
                            lbThongBaoXoa.Text = ex.ToString();
                            OpenDialog("#thongbaoxoa");
                            upDatePanelThongBaoXoa.Update();
                            cmdAgree.Visible = false;
                            cmdClose.Text = "Đóng lại";
                        }
                    }
                }
            }
        }
        protected void cmdSerach_Click(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                StrAlert += "<div class='alert alert-warning'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Vui lòng nhập vào từ khoá để tìm kiếm !";
                StrAlert += "</div>";
            }
            else
            {
                Search(txtSearch.Text);
            }
        }
        protected void cmdRefesh_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
            BindGridUnitVehicle();
        }
        protected void cmdExport_Click(object sender, EventArgs e)
        {
            OpenDialog("#exporttoexcel");
        }
        protected void cmdExportToExcel_Click(object sender, EventArgs e)
        {
        }
        //---------------button-popup---------------------
        protected void imgrefesh_Click(object sender, ImageClickEventArgs e)
        {
            drKhoi.Items.Clear();
            drKhoi.Items.Add(new ListItem("--Vui lòng chọn khối--", "-1"));
            BindGridBlockVehicle();
        }
        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            if (txtMaDonViTinh.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào mã đơn vị tính !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtTenDonViTinh.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào tên đơn vị tính !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drKhoi.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn khối !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtTrongTai.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào trọng tải !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtMaDonViTinh.Text != "" && txtTenDonViTinh.Text != "" && txtTrongTai.Text != "" && drKhoi.SelectedValue.ToString() != "-1")
            {
                Insert();
            }
        }
        protected void cmdAgree_Click(object sender, EventArgs e)
        {
            
        }
        protected void cmdClose_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbaoxoa");
        }
        protected void cmdCloseThongBao_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbao");
        }
        protected void ImgRefeshDuyet_Click(object sender, ImageClickEventArgs e)
        {

        }
        protected void ImgRefeshExport_Click(object sender, ImageClickEventArgs e)
        {
            //txtTuNgayNhapKhoExport.Text = "";
            //txtDenNgayNhapKhoExport.Text = "";
            //BindGridLenhDieuDongExportExcel();
        }
        //-------------list-view-----------------------
        protected void ListViewAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                HttpCookie cookie = Request.Cookies["UserLogin"];
                bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyDonViTinhLoaiXe, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                lbThongBaoLoi.Text = "";
                txtMaDonViTinh.Enabled = false;
                if (e.CommandName == "Accept")
                {
                    if (Edit == false)
                    {
                        imgSave.Visible = false;
                        string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridUnitVehicleDetail_Edit(int.Parse(SenderId));
                        OpenDialog("#donvitinhxe");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                    else
                    {
                        imgSave.Visible = true;
                        string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridUnitVehicleDetail_Edit(int.Parse(SenderId));
                        OpenDialog("#donvitinhxe");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void ListViewAll_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                LinkButton linkListName = (LinkButton)e.Item.FindControl("linkListName");
                LinkButton linkListName_F = (LinkButton)e.Item.FindControl("linkListName_F");
                string _jsDouble1 = ClientScript.GetPostBackClientHyperlink(linkListName, "");

                linkListName.Attributes["ondblclick"] = _jsDouble1;
                linkListName.Attributes["onclick"] = "return false;";
            }
        }
        //-----------pagger-----------------------
        protected void DataPagerListAll_PreRender(object sender, EventArgs e)
        {
            BindGridUnitVehicle();
        }
        //---------Check-all--------------
        protected void chkCheckAll_CheckedChanged(object sender, EventArgs e)
        {

        }
        //---------Dropdownlist-----------
        protected void drTrongTai_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }
        //----------Thêm-nhanh------------
        protected void linkThemNhanh_Click(object sender, EventArgs e)
        {
            OpenDialog("#themnhanh");
        }
        #endregion

        #region[Function]
        protected void BindGridUnitVehicle()
        {
            dtUnitVehicle = clsUnitVehicle.Search(txtSearch.Text);
            if (dtUnitVehicle != null && dtUnitVehicle.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtUnitVehicle;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
            }
        }
        protected void BindGridUnitVehicleDetail_Edit(int id)
        {
            dtUnitVehicleDetail = clsUnitVehicle.BindGirdTMUnit_Vehicle_Detail_Edit(id);
            if (dtUnitVehicleDetail != null && dtUnitVehicleDetail.Rows.Count > 0)
            {
                lbID.Text = dtUnitVehicleDetail.Rows[0]["STT"].ToString();
                lbIDXoa.Text = dtUnitVehicleDetail.Rows[0]["STT"].ToString();
                txtMaDonViTinh.Text = dtUnitVehicleDetail.Rows[0]["Unit_Vehicle_Alias"].ToString();
                txtTenDonViTinh.Text = dtUnitVehicleDetail.Rows[0]["Unit_Vehicle_Name"].ToString();
                txtTrongTai.Text = String.Format("{0:0.0}", dtUnitVehicleDetail.Rows[0]["Unit_Vehicle_Number"]).ToString();
                drKhoi.SelectedValue = dtUnitVehicleDetail.Rows[0]["Unit_Block_Vehicle_ID"].ToString();
            }
        }
        protected void BindGridBlockVehicle()
        {
            dtBlockVehicle = clsBockVehicle.BindGirdTMBock_Vehicle();
            if (dtBlockVehicle != null && dtBlockVehicle.Rows.Count > 0)
            {
                drKhoi.DataSource = dtBlockVehicle;
                drKhoi.DataTextField = "Block_Vehicel_Alias";
                drKhoi.DataValueField = "Block_Vehicle_ID";
                drKhoi.DataBind();
            }
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            dtUnitVehicle = clsUnitVehicle.BindGirdTMUnit_Vehicle();
            if (dtUnitVehicle != null && dtUnitVehicle.Rows.Count > 0)
            {
                foreach (DataRow dr in dtUnitVehicle.Rows)
                {
                    if (txtMaDonViTinh.Text == dr["Unit_Vehicle_Alias"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected void Insert()
        {
            //Insert
            if (flag)
            {
                InsertUnitVehicle();
            }
            else//Update
            {
                UpdateUnitVehicle();
            }
        }
        protected void InsertUnitVehicle()
        {
            try
            {
                if (CheckInsert())
                {
                    lbThongBaoLoi.Text = "Mã đơn vị tính này đã tồn tại !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
                else
                {
                    VanTaiProperty.clsTMUnit_VehicleProperty obj = new clsTMUnit_VehicleProperty();
                    obj.Unit_Vehicle_Alias = txtMaDonViTinh.Text;
                    obj.Unit_Vehicle_Name = txtTenDonViTinh.Text;
                    obj.Unit_Vehicle_Number = float.Parse(txtTrongTai.Text.Replace(",", ""));
                    obj.Unit_Block_Vehicle_ID = int.Parse(drKhoi.SelectedValue.ToString());
                    VanTaiBLL.clsTMUnit_VehicleBusiness.InsertTMUnit_Vehicle(obj);
                    lbThongBaoLoi.Text = "Thêm mẫu tin thành công !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                    BindGridUnitVehicle();
                    ClearTextBox();
                    ClearDropdownlist();
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void UpdateUnitVehicle()
        {
            try
            {
                VanTaiProperty.clsTMUnit_VehicleProperty obj = new clsTMUnit_VehicleProperty();
                obj.Unit_Vehicle_ID = int.Parse(lbID.Text);
                obj.Unit_Vehicle_Alias = txtMaDonViTinh.Text;
                obj.Unit_Vehicle_Name = txtTenDonViTinh.Text;
                obj.Unit_Vehicle_Number = float.Parse(txtTrongTai.Text.Replace(",", ""));
                obj.Unit_Block_Vehicle_ID = int.Parse(drKhoi.SelectedValue.ToString());
                VanTaiBLL.clsTMUnit_VehicleBusiness.UpdateTMUnit_Vehicle(obj);
                lbThongBaoLoi.Text = "Cập nhật mẫu tin thành công !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
                BindGridUnitVehicle();
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        //AutoComplate
        protected void Autocomplate()
        {
            dtAutoComplete = clsUnitVehicle.BindGirdTMUnit_Vehicle();
            if (dtAutoComplete != null && dtAutoComplete.Rows.Count > 0)
            {
                foreach (DataRow dr in dtAutoComplete.Rows)
                {
                    if (string.IsNullOrEmpty(SuggestionList))
                    {
                        SuggestionList += "\"" + dr["Unit_Vehicle_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["Unit_Vehicle_Alias"].ToString().Replace("\n", " ") + "\",";
                    }
                    else
                    {
                        SuggestionList += "\"" + dr["Unit_Vehicle_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["Unit_Vehicle_Alias"].ToString().Replace("\n", " ") + "\",";
                    }
                }
            }
        }
        protected void Search(string keywords)
        {
            dtSearch = clsUnitVehicle.Search(keywords);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtSearch;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;

                StrAlert += "<div class='alert alert-success'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Tìm thấy " + dtSearch.Rows.Count.ToString() + " mẫu tin !";
                StrAlert += "</div>";
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
                StrAlert += "<div class='alert alert-error'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Không tìm thấy mẫu tin nào !";
                StrAlert += "</div>";
            }
        }
        //Total
        #endregion

        #region[OpenDialog]
        private void OpenDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        private void CloseDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('close');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        #endregion

        #region[Clear-TextBox]
        protected void ClearTextBox()
        {
            txtMaDonViTinh.Text = "";
            txtTenDonViTinh.Text = "";
            txtTrongTai.Text = "0";
        }
        protected void ClearDropdownlist()
        {
            drKhoi.SelectedIndex = -1;
        }
        #endregion

        #region[Permisstion]
        protected void CheckPermisstion()
        {
            HttpCookie cookie = Request.Cookies["UserLogin"];
            if (cookie != null)
            {
                bool Is_Page_All = SecurityServices.HasPermisstionPage(StringContent.QuanLyDonViTinhLoaiXe, int.Parse(cookie["RolesID"]), true);
                if (Is_Page_All == true)
                {
                    bool AddNew = SecurityServices.HasPermisstion(StringContent.QuanLyDonViTinhLoaiXe, int.Parse(cookie["RolesID"]), TypeaAudit.AddNew);
                    if (AddNew == false)
                    {
                        cmdAddNew.Visible = false;
                    }
                    else
                    {
                        cmdAddNew.Visible = true;
                    }
                    bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyDonViTinhLoaiXe, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                    if (Edit == false)
                    {
                        cmdEdit.Visible = false;
                    }
                    else
                    {
                        cmdEdit.Visible = true;
                    }
                    bool Del = SecurityServices.HasPermisstion(StringContent.QuanLyDonViTinhLoaiXe, int.Parse(cookie["RolesID"]), TypeaAudit.Delete);
                    if (Del == false)
                    {
                        cmdDel.Visible = false;
                    }
                    else
                    {
                        cmdDel.Visible = true;
                    }
                }
                else
                {
                    Response.Redirect("error-page.aspx");
                }
            }
        }
        #endregion
    }
}